<?php

class Paging extends Data
{
    public function __construct($params=array())
    {
        if(!is_array($params)) $this->error='В обработчик данных Paging переданы неправильные параметры. Это должен быть массив';
        else{
            if(isset($params['options'])){
                $this->classOptions=$params['options'];
                unset($params['options']);
            }elseif(isset($params['htmlOptions'])){
                $this->classOptions=$params['htmlOptions'];
                unset($params['htmlOptions']);
            }else{
                foreach($params as $name=>$value){
                    if(is_string($name) && strlen($name)>1 && $name!='limit' && $name!='model'){
                        $this->classOptions[$name]=$value;
                        unset($params[$name]);
                    }
                }
            }
        }

        if(!$this->classOptions || !isset($this->classOptions['pagingCount'])) $this->classOptions['pagingCount']=Sys::app()->config->paging->pagingCount;

        if($limit=Sys::app()->request->param('limit')) $this->params['limit']=$limit;
        elseif(!$this->params['limit']) $this->params['limit']=Sys::app()->config->paging->dataLimit;

        if(isset($params['model'])){
            $this->setModel($params['model']);
            unset($params['model']);
        }elseif(isset($params[0]) && (is_string($params[0] || is_object($params[0])))){
            $this->setModel($params[0]);
            if($this->model) unset($params[0]);
        }

        if($this->params) $this->params=array_merge($this->params,$params);
        else $this->params=$params;
    }

    public function getPagingLinks($model='',$params=array())
    {
        if(!$params && is_array($model)){
            $params=$model;
            $model=null;
        }
        if($model && (is_object($model) || is_string($model))) $this->setModel($model);
        if(!$model=$this->model){
            Sys::app()->error='В обработчик данных Paging не перадана модель';
            return false;
        }

        if(!$params) $params=$this->params;
        else $this->params=$params;

        $paramsNoLimit=$params;
        unset($paramsNoLimit['limit']);
        if(!$totalLinesNumber=$this->model->getCount($paramsNoLimit)) return false;
        unset($paramsNoLimit);

        if(!$view=$this->checkView()) return false;

        $modelClassName=get_class($model);
        $limit=self::getLinesPerPage($params);
        $linesPerPage=$limit['limit'];
        $startPos=$limit['start'];
        if($startPos>$totalLinesNumber) $startPos=$totalLinesNumber-$linesPerPage;
        elseif($startPos<1) $startPos=0;
        if($linesPerPage>$totalLinesNumber) $linesPerPage=$totalLinesNumber;

        if(!$linesPerPage) return false;

        $pagesCount=ceil($totalLinesNumber/$linesPerPage);
        if($pagesCount==1) return false;

        $pagingCount=$this->classOptions['pagingCount'];
        $maxLimit=($pagesCount-1)*$linesPerPage;

        $html=Widget::html();
        $currentRoute=Sys::app()->request->route;

        $beforeAndAfterPagesNum=floor($pagingCount/2)*$linesPerPage;

        if($startPos<=$beforeAndAfterPagesNum){
            $startPageNum=0;
        }elseif($startPos>$totalLinesNumber-$linesPerPage){
            $startPageNum=($totalLinesNumber-$linesPerPage)/$linesPerPage;
        }else{
            $startPageNum=ceil(($startPos-$beforeAndAfterPagesNum)/$linesPerPage);
        }
        $endPageNum=$startPageNum+$pagingCount;

        if($endPageNum>=$pagesCount){
            $endPageNum=$pagesCount;
            $startPageNum=$endPageNum-$pagingCount;
        }
        if($startPageNum<0) $startPageNum=0;

        $pagingLinks=array();
        for($i=$startPageNum;$i<$endPageNum;$i++){
            $limit=$i*$linesPerPage;
            if($limit>$totalLinesNumber-$linesPerPage){
                $limit=$maxLimit;
            }
            $class=$limit==$startPos ? 'pagination-button button active' : 'pagination-button button';

            if($limit>0) $limit=$limit.', '.$linesPerPage;
            else $limit=$linesPerPage;
            $num=$i+1;

            $options=array(
                'linkName'=>$num,
                'elementId'=>$modelClassName.'-paging-'.$num,
                'class'=>$class,
                'limit'=>$limit,
            );
            //if(self::$ajax) $options['onClick']='return Data.pagination(this,true);';

            $pagingLinks[$i]=$html->link($currentRoute,array_merge($params,$options));
        }

        $nextLinkPageNum=$startPos+$linesPerPage;
        if($nextLinkPageNum>$totalLinesNumber-$linesPerPage) $nextLinkPageNum=$maxLimit;
        $nextLimit=$nextLinkPageNum.', '.$linesPerPage;

        $pervLinkPageNum=$startPos-$linesPerPage;
        if($pervLinkPageNum<0) $pervLinkPageNum=0;
        if($pervLinkPageNum==0) $pervLimit=$linesPerPage;
        else $pervLimit=$pervLinkPageNum.', '.$linesPerPage;

        $viewParams=array(
            'id'=>$modelClassName.'-paging',
            'class'=>'paging',
            'paginationLinks'=>$pagingLinks,
            'toBeginLink'=>$html->link($currentRoute,array_merge($params,array(
                'elementId'=>$modelClassName.'-paging-to-begin',
                'class'=>'pagination-button button first',
                'linkName'=>'<<',
                'limit'=>$linesPerPage,
            ))),
            'pervLink'=>$html->link($currentRoute,array_merge($params,array(
                'elementId'=>$modelClassName.'-paging-perv',
                'class'=>'pagination-button button',
                'linkName'=>'<',
                'limit'=>$pervLimit,
            ))),
            'nextLink'=>$html->link($currentRoute,array_merge($params,array(
                'elementId'=>$modelClassName.'-paging-next',
                'class'=>'pagination-button button',
                'linkName'=>'>',
                'limit'=>$nextLimit,
            ))),
            'toEndLink'=>$html->link($currentRoute,array_merge($params,array(
                'elementId'=>$modelClassName.'-paging-to-end',
                'class'=>'pagination-button button last',
                'linkName'=>'>>',
                'limit'=>$maxLimit.', '.$linesPerPage,
            ))),
        );

        return $this->renderView($view,$viewParams);
    }
}